package com.xp.gather2.client;


import com.xp.gather2.comment.utils.DateUtils;
import com.xp.gather2.entity.Lamp;
import com.xp.gather2.entity.Lampstate;
import com.xp.gather2.service.LampstateService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Component
@Slf4j
@ChannelHandler.Sharable
public class LampHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    LampstateService lampStateService;
    public static boolean ISCONNECT = false;
    public static boolean STATE = true;
    public static String lampID = "";
    Lampstate lampState = new Lampstate();

    // 写数据相关的逻辑省略
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf byteBuf = (ByteBuf) msg;
        String res =  byteBuf.toString(Charset.forName("utf-8"));
        log.info("客户端读到数据 -> " +res);
        lampState.setLampId(new Lamp(lampID));
        if("OK".equals(res.split(" ")[0])){
            if(res.split("=")[1].substring(1,2).equals("c")){
                lampState.setState("关");
            }else{
                lampState.setState("开");
            }
        }else {
            lampState.setState("异常");
        }
        lampState.setTime(DateUtils.getCurrentDateFormat());
        lampStateService.insert(lampState);
        STATE=false;
        ReferenceCountUtil.release(byteBuf);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接成功");
        ISCONNECT=true;
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ISCONNECT=false;
        log.info("channel 被关闭：channelInactive()");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ISCONNECT=false;
        log.info("channel 取消线程(NioEventLoop) 的绑定: channelUnregistered()");
        super.channelUnregistered(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        ISCONNECT=false;
        log.info("逻辑处理器被移除：handlerRemoved()");
        super.handlerRemoved(ctx);
    }

}
